package com.guang.springbootexception.exceptionresolver;

import com.guang.springbootexception.exception.ServiceException;
import com.guang.springbootexception.exception.ServiceExceptions;
import com.guang.springbootexception.restful.RestHttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ExceptionControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    public ExceptionControllerAdvice() {
    }

    /**
     * 接收得到所有的异常信息
     * @param t
     * @return
     */
    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.OK)
    public RestHttpEntity<Object> buildErrorMessage(Throwable t) {
        // 如果是业务上的异常，那么应该来进行打印输出！
        if (t instanceof ServiceException) {
            ServiceException serviceException = (ServiceException)t;
            return RestHttpEntity.buildFailResponse(serviceException);
        } else {
            // 如果是编码上的异常，那么应该抛出对应的异常之后，做一下记录
            logger.error("未捕获异常", t);
            return RestHttpEntity.buildFailResponse(ServiceExceptions.F999.buildServiceException());
        }
    }
}